package com.xhwl.data.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.xhwl.common.dto.cent.sdata.*;
import com.xhwl.common.enums.LogOperationTypeEnum;
import com.xhwl.common.enums.ModuleTypeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.enums.config.RoleTypeEnum;
import com.xhwl.common.enums.sdata.EnterpriseTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.AbstractAccount;
import com.xhwl.common.pojo.cent.sdata.personnel.Staff;
import com.xhwl.common.pojo.cent.sdata.personnel.StaffOrganization;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.common.utils.CentDataVerifyUtil;
import com.xhwl.common.vo.cent.sdata.EnterpriseRentVO;
import com.xhwl.common.vo.cent.sdata.ProjectPermissionVO;
import com.xhwl.data.dao.personal.IStaffDao;
import com.xhwl.data.dao.personal.IStaffOrganizationDao;
import com.xhwl.data.mq.producer.EntPermissionProducer;
import com.xhwl.data.pojo.dto.personal.EnterpriseTreeDTO;
import com.xhwl.data.pojo.vo.CustomerInformationVO;
import com.xhwl.data.service.personal.IStaffService;
import com.xhwl.starter.log.LogTemplate;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.query.cent.sdata.EnterpriseQuery;
import com.xhwl.common.query.cent.sdata.RoleQuery;
import com.xhwl.common.utils.ThreadLocalUtil;
import com.xhwl.data.dao.*;
import com.xhwl.data.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description: 企业管理
 * @author: lianghz
 * @create: 2020-11-25
 **/
@Service
public class EnterpriseServiceImpl extends ServiceImpl<IEnterpriseDao, Enterprise> implements IEnterpriseService {

    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IEnterprisePermissionService enterprisePermissionService;
    @Autowired
    private IEnterpriseAppService enterpriseAppService;
    @Autowired
    private IRolePermissionService rolePermissionService;
    @Autowired
    private IEnterpriseDao enterpriseDao;
    @Autowired
    private IOrganizationDao organizationDao;
    @Autowired
    IAccountOrganizationDao accountOrganizationDao;
    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private IProjectDao projectDao;

    @Autowired
    private IPermissionDao permissionDao;

    @Autowired
    private IProjectPermissionService projectPermissionService;

    @Autowired
    LogTemplate logTemplate;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IAccountRoleService accountRoleService;

    @Autowired
    private IEnterpriseProjectService enterpriseProjectService;

    @Autowired
    private IEnterpriseSpaceService enterpriseSpaceService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    @Autowired
    private IStaffDao staffDao;

    @Autowired
    private IStaffOrganizationDao staffOrganizationDao;

    @Autowired
    private IPermissionGroupDao permissionGroupDao;

    @Autowired
    private EntPermissionProducer entPermissionProducer;

    @Autowired
    private IAccountProjectService accountProjectService;

    private static final Logger log = LoggerFactory.getLogger(EnterpriseServiceImpl.class);

    private static final List<String> EXCLUDE_ENTERPRISE_PERMISSION = Arrays.asList("enterpriseAdd", "enterpriseModify");

    @Autowired
    private IEnterpriseExtraService enterpriseExtraService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IProjectService projectService;

    @Autowired
    private IStaffService staffService;

    @Autowired
    IAccountDao accountDao;

    @Autowired
    private IOrganizationSpaceService organizationSpaceService;

    @Autowired
    private ISceneEnterpriseDao sceneEnterpriseDao;

    /**
     * 创建企业管理员帐号
     * @param enterpriseAccount 需要创建的帐号
     * @param account 操作帐号
     * @param enterpriseDTO
     * @param enterprise
     * @param managerRoleId
     */
    private void createMangerAccount(AccountDTO enterpriseAccount, Account account, EnterpriseDTO enterpriseDTO, Enterprise enterprise, Integer managerRoleId){
        //未填写登录名或填写不符合规则
        if (StringUtils.isEmpty(enterpriseAccount.getLoginName())) {
            String loginName = UUID.randomUUID().toString().replaceAll("-", "").substring(0,20);
            enterpriseAccount.setLoginName(loginName);
        }
        Integer managerAccountId = 0;
        Account account1 = null;
        //先查询是否存在此账户
        if(!StringUtils.isEmpty(enterpriseAccount.getPhone())) {
            account1 = accountService.phoneExistV2(enterpriseAccount.getPhone(), enterpriseDTO.getDevelopId());
        }
        if(account1!=null){
            managerAccountId = account1.getId();
            // 给已存在的帐号添加当前企业管理员的角色
            managerRoleAccountBind(account1.getId(), managerRoleId,enterprise.getId());
            // 绑定企业组织和帐号的关系
            AccountOrganization accountOrganization = new AccountOrganization();
            accountOrganization.setEnterpriseId(enterprise.getId());
            accountOrganization.setType(OrganizationTypeEnum.ENTERPRISE.id.intValue());
            accountOrganization.setAccountId(account1.getId());
            accountOrganization.setOrganizationId(enterprise.getOrganizationId());
            accountOrganizationDao.insert(accountOrganization);
        } else {
            managerAccountId = createManagerAccount(enterpriseDTO.getIndustryId(), enterprise.getId(), enterpriseAccount);
        }
        // 保存企业管理员的员工帐号信息 和 企业组织关系
        enterpriseAccount.setId(managerAccountId);
        createStaff(enterpriseAccount, enterprise);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson<Integer> create(EnterpriseDTO enterpriseDTO, List<Integer> permissions, Account account) {
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(enterpriseDTO, enterprise);
        // 企业类型
        if (!CollectionUtils.isEmpty(enterpriseDTO.getTypes())) {
            enterprise.setType(Joiner.on(",").join(enterpriseDTO.getTypes()));
        }
        ResultJson resultJson = saveCheck(enterprise);
        if (!resultJson.getState()) {
            return resultJson;
        }
        if (StringUtils.isEmpty(enterprise.getCode())){
            String code = UUID.randomUUID().toString().replaceAll("-", "");
            enterprise.setCode(code.substring(code.length()-8));
        }
        enterpriseDao.insert(enterprise);
        enterpriseDTO.setId(enterprise.getId());
        permissions = this.savePermissions(permissions, enterpriseDTO);
        // 创建组织
        createOrganization(enterprise, account);
        enterpriseDao.updateById(enterprise);
        // 创建企业管理员角色
        Integer managerRoleId = this.createManagerRole(enterprise, permissions);

        //创建企管账号及帐号相关信息
        AccountDTO enterpriseAccount = enterpriseDTO.getAdminAccount();
        if (null != enterpriseAccount) {
            if (!StringUtils.isEmpty(enterpriseAccount.getLoginName())){
                CentDataVerifyUtil.loginNameVerify(enterpriseAccount.getLoginName());
            }
            createMangerAccount(enterpriseAccount, account, enterpriseDTO, enterprise, managerRoleId);
        }
        createEnterpriseApp(permissions, enterprise);
        //添加场景关系
        createSceneEnterprise(enterpriseDTO.getSceneIds(),enterprise.getId());
        // 保存入驻企业信息
        saveEnterpriseEnter(enterprise, enterpriseDTO);
        //保存企业扩展信息
        enterpriseExtraService.save(enterprise.getId(), enterpriseDTO.getExtra());
        // 非运营商企业
        if(!CollectionUtils.isEmpty(enterpriseDTO.getTypes()) && !enterpriseDTO.getTypes().contains(EnterpriseTypeEnum.OPERATOR.id.intValue())){
            projectService.bindProject(enterprise.getId(),enterpriseDTO.getAuthProjectIds(),true);
        }
        // 下发企业、权限信息
        sendTenantToMQ("create", enterprise, permissions);
        //记录日志
        enterpriseLogRecord(account, LogOperationTypeEnum.CREATE, "新增企业" + "【" + enterprise.getName() + "】", enterprise.getId());
        return ResultJson.successWithResult(enterprise.getId());
    }

    /**
     * 创建企业与场景关联
     */
    private void createSceneEnterprise(List<Integer> sceneIds, Integer entId) {
        if (CollectionUtils.isEmpty(sceneIds)) {
            return;
        }
        //先删后增加
        QueryWrapper delQueryWrapper = new QueryWrapper();
        delQueryWrapper.eq("enterprise_id",entId);
        sceneEnterpriseDao.delete(delQueryWrapper);
        SceneEnterprise sceneEnterprise = null;
        for(Integer id:sceneIds){
            sceneEnterprise = new SceneEnterprise();
            sceneEnterprise.setEnterpriseId(entId);
            sceneEnterprise.setSceneId(id);
            sceneEnterpriseDao.insert(sceneEnterprise);
        }
    }

    /**
     * 给帐号绑定角色 给企业管理员帐号绑定企业管理员角色
     * @param accountId
     * @param roleId
     */
    private void managerRoleAccountBind( Integer accountId, Integer roleId,Integer entId){
        AccountRole accountRole = new AccountRole();
        accountRole.setRoleId(roleId);
        accountRole.setAccountId(accountId);
        accountRoleService.save(accountRole);

        // 增加权限组
        PermissionGroup permissionGroup = new PermissionGroup();
        permissionGroup.setAccountId(accountId);
        permissionGroup.setRoleIds(roleId.toString());
        permissionGroup.setEnterpriseId(entId);
        permissionGroupDao.insert(permissionGroup);
    }


    /**
     * 创建企业时默认创建帐号时默认创建企业员工身份
     * @param enterpriseAccount
     * @param enterprise
     */
    private void createStaff(AccountDTO enterpriseAccount, Enterprise enterprise) {
        if(staffIsExist(enterpriseAccount.getId(), enterprise.getId())){
            log.info("当前员工帐号 {} 已经在企业 {} 下存在员工信息", enterpriseAccount.getId(), enterprise.getId());
            return;
        }
        Staff staff = new Staff();
        staff.setAccountId(enterpriseAccount.getId());
        staff.setDeleted(false);
        staff.setShowPhone(true);
        staff.setName(enterpriseAccount.getName());
        staffDao.insert(staff);
        StaffOrganization staffOrganization = new StaffOrganization();
        staffOrganization.setAccountId(enterpriseAccount.getId());
        staffOrganization.setStaffId(staff.getId());
        staffOrganization.setOrgId(enterprise.getOrganizationId());
        staffOrganization.setEnterpriseId(enterprise.getId());
        staffOrganizationDao.insert(staffOrganization);
    }


    /**
     * 判断员工信息是否在当前企业下已经存在
     * @param accountId
     * @param enterpriseId
     * @return
     */
    private boolean staffIsExist(Integer accountId, Integer enterpriseId){
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.select("id");
        staffOrganizationQueryWrapper.eq("account_id", accountId);
        staffOrganizationQueryWrapper.eq("enterprise_id", enterpriseId);
        List<StaffOrganization> staffOrganizations = staffOrganizationDao.selectList(staffOrganizationQueryWrapper);
        return !CollectionUtils.isEmpty(staffOrganizations);
    }

    /**
     * 保存入驻企业信息
     *
     * @param enterprise
     * @param enterpriseDTO
     */
    private void saveEnterpriseEnter(Enterprise enterprise, EnterpriseDTO enterpriseDTO) {
        if (null == enterprise.getParentId()) {
            return;
        }
        // 项目授权
        if (enterprise.getType().contains(EnterpriseTypeEnum.OPERATOR.id.toString())){
            //运营商授权所有项目
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("enterprise_id",enterprise.getId());
            projectQueryWrapper.eq("is_deleted",false);
            List<Project> projects = projectService.list(projectQueryWrapper);
            if (!projects.isEmpty()){
                enterpriseDTO.setAuthProjectIds(projects.stream().map(Project::getId).collect(Collectors.toList()));
            }
        }
        // 项目授权
        saveEnterpriseProject(enterprise, enterpriseDTO);
        // 入驻空间
        saveEnterpriseEnterSpace(enterprise, enterpriseDTO);
        // 保存入驻企业在项目下的权限
        if(!EnterpriseTypeEnum.OPERATOR.id.toString().equals(enterprise.getType())){
            saveEnterprisePermissionProject(enterprise, enterpriseDTO);
        }
    }

    /**
     * 保存入驻企业在项目下的权限
     *
     * @param enterprise
     * @param enterpriseDTO
     */
    private void saveEnterprisePermissionProject(Enterprise enterprise, EnterpriseDTO enterpriseDTO) {
        // 先删除 com.xhwl.data.service.IEnterprisePermissionService.saveV2 已经删除了
//        QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
//        enterprisePermissionQueryWrapper.eq("enterprise_id", enterprise.getId());
//        enterprisePermissionQueryWrapper.isNotNull("project_id");
//        enterprisePermissionService.remove(enterprisePermissionQueryWrapper);

        if (CollectionUtils.isNotEmpty(enterpriseDTO.getProjectPermissionVOS())) {
            List<ProjectPermissionVO> projectPermissionVOS = enterpriseDTO.getProjectPermissionVOS();
            List<Integer> permissionIds1 = new ArrayList<>();
            for (ProjectPermissionVO projectPermissionVO : projectPermissionVOS) {
                if (!CollectionUtils.isEmpty(projectPermissionVO.getPermissionIds())) {
                    permissionIds1.addAll(projectPermissionVO.getPermissionIds());
                }
            }
            if(permissionIds1.isEmpty()){
                log.info("未勾选项目权限");
                return ;
            }
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.in("id", permissionIds1.stream().distinct().collect(Collectors.toList()));
            permissionQueryWrapper.and(wrapper -> wrapper.eq("type", 2).or().isNull("type"));
            List<Permission> permissions = permissionDao.selectList(permissionQueryWrapper);
            if (permissions.isEmpty()) {
                log.warn("权限中没有项目范围权限");
                return;
            }
            Map<Integer, String> permissionMap = permissions.stream().collect(Collectors.toMap(Permission::getId, Permission::getName));
            List<EnterprisePermission> enterprisePermissions = new ArrayList<>();
            for (ProjectPermissionVO projectPermissionVO : projectPermissionVOS) {
                List<Integer> permissionIds = projectPermissionVO.getPermissionIds();
                if (CollectionUtils.isNotEmpty(permissionIds)) {
                    for (Integer permissionId : permissionIds) {
                        // 过滤不是项目权限范围
                        if (StringUtils.isEmpty(permissionMap.get(permissionId))) {
                            continue;
                        }
                        EnterprisePermission enterprisePermission = new EnterprisePermission();
                        enterprisePermission.setEnterpriseId(enterprise.getId());
                        enterprisePermission.setPermissionId(permissionId);
                        enterprisePermission.setProjectId(projectPermissionVO.getProjectId());
                        enterprisePermissions.add(enterprisePermission);
                    }
                }
            }
            enterprisePermissionService.saveBatch(enterprisePermissions);
        }
    }

    /**
     * 保存企业入驻空间信息
     *
     * @param enterprise
     * @param enterpriseDTO
     */
    private void saveEnterpriseEnterSpace(Enterprise enterprise, EnterpriseDTO enterpriseDTO) {
        //先删后增 或者是去掉入驻企业身份后删除租赁空间
        QueryWrapper<EnterpriseSpace> enterpriseSpaceQueryWrapper = new QueryWrapper<>();
        enterpriseSpaceQueryWrapper.eq("enterprise_id", enterprise.getId());
        enterpriseSpaceService.remove(enterpriseSpaceQueryWrapper);
        List<Organization> organizationList = organizationService.list(new OrganizationQuery().withEnterpriseId(enterprise.getId()).withTypes(Collections.singletonList(4)));
        List<Integer> orgIds = organizationList.stream().map(Organization::getId).collect(Collectors.toList());
        QueryWrapper<OrganizationSpace> organizationSpaceQueryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(enterpriseDTO.getRentSpace())) {
            List<Integer> rentSpace = enterpriseDTO.getRentSpace();

            QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
            organizationQueryWrapper.in("id", rentSpace);
            organizationQueryWrapper.in("type", organizationTypeService.spaceIds());
            List<Organization> list = organizationService.list(organizationQueryWrapper);
            if (!list.isEmpty()) {
                List<Integer> collect = list.stream().map(i -> i.getId()).collect(Collectors.toList());
                List<Integer> collect1 = rentSpace.stream().filter(i -> collect.contains(i)).collect(Collectors.toList());
                if (!collect1.isEmpty()) {
                    List<EnterpriseSpace> enterpriseSpaces = new ArrayList<>(collect1.size());
                    for (Integer integer : collect1) {
                        EnterpriseSpace enterpriseSpace = new EnterpriseSpace();
                        enterpriseSpace.setEnterpriseId(enterprise.getId());
                        enterpriseSpace.setOrganizationId(integer);
                        if (null != enterpriseDTO.getEnterpriseRentDTOS() && !enterpriseDTO.getEnterpriseRentDTOS().isEmpty()){
                            for (EnterpriseRentDTO enterpriseRentDTO : enterpriseDTO.getEnterpriseRentDTOS()){
                                if (null != enterpriseRentDTO.getRentEndTime() && null != enterpriseRentDTO.getRentStartTime()){
                                    if (enterpriseRentDTO.getSpaceIds().contains(integer)){
                                        enterpriseSpace.setRentStartTime(enterpriseRentDTO.getRentStartTime());
                                        enterpriseSpace.setRentEndTime(enterpriseRentDTO.getRentEndTime());
                                    }
                                }
                            }
                        }
                        enterpriseSpaces.add(enterpriseSpace);
                    }
                    // 保存租赁空间
                    enterpriseSpaceService.saveBatch(enterpriseSpaces);
                }
            }
        }else {
            if (!orgIds.isEmpty()){
                organizationSpaceQueryWrapper.in("organization_id",orgIds);
            }
        }
        //同步删除
        if (null != enterpriseDTO.getDeleteRentSpace() && !enterpriseDTO.getDeleteRentSpace().isEmpty() && !orgIds.isEmpty()){
            //同步删除组织关联空间
            organizationSpaceQueryWrapper.in("organization_id",orgIds);
            organizationSpaceQueryWrapper.in("space_id",enterpriseDTO.getDeleteRentSpace());
            //同步删除员工空间权限
            QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
            accountOrganizationQueryWrapper.in("organization_id",enterpriseDTO.getDeleteRentSpace());
            accountOrganizationQueryWrapper.eq("enterprise_id", enterprise.getId());
            accountOrganizationDao.delete(accountOrganizationQueryWrapper);
        }
        organizationSpaceService.remove(organizationSpaceQueryWrapper);
    }
    /**
     * 移除服务商企业授权的项目
     *
     * @param enterpriseId
     */
    private void removeEnterpriseProject(Integer enterpriseId) {
        QueryWrapper<EnterpriseProject> enterpriseProjectQueryWrapper = new QueryWrapper<>();
        enterpriseProjectQueryWrapper.eq("enterprise_id", enterpriseId);
        enterpriseProjectService.remove(enterpriseProjectQueryWrapper);
    }

    /**
     * 保存项目授权信息
     *
     * @param enterprise
     * @param enterpriseDTO
     */
    private void saveEnterpriseProject(Enterprise enterprise, EnterpriseDTO enterpriseDTO) {
        // 清除授权的项目信息
        removeEnterpriseProject(enterprise.getId());
        // 保存授权项目信息
        if (CollectionUtils.isNotEmpty(enterpriseDTO.getAuthProjectIds())) {
            // 获取运营商企业的项目信息
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("enterprise_id", enterprise.getParentId());
            projectQueryWrapper.eq("is_deleted", false);
            List<Project> projects = projectDao.selectList(projectQueryWrapper);
            if (CollectionUtils.isNotEmpty(projects)) {
                List<Integer> collect = projects.stream().map(i -> i.getId()).collect(Collectors.toList());
                // 交集传入的项目id和运营商所有的项目id
                List<Integer> collect1 = enterpriseDTO.getAuthProjectIds().stream().filter(i -> collect.contains(i)).collect(Collectors.toList());
                if (!collect1.isEmpty()) {
                    // 保存服务商企业和项目之间的关系
                    List<EnterpriseProject> enterpriseProjects = new ArrayList<>(collect1.size());
                    for (Integer integer : collect1) {
                        EnterpriseProject enterpriseProject = new EnterpriseProject();
                        enterpriseProject.setEnterpriseId(enterprise.getId());
                        enterpriseProject.setProjectId(integer);
                        enterpriseProjects.add(enterpriseProject);
                    }
                    enterpriseProjectService.saveBatch(enterpriseProjects);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson delete(Integer id, Account account) {
        Enterprise enterprise = this.getOne(id, account);
        if (null == enterprise) {
            return ResultJson.fail("企业不存在");
        }
        enterprise.setIsDeleted(true);
        int i = enterpriseDao.updateById(enterprise);
        if (0 == i) {
            return ResultJson.fail("数据错误");
        }
        delete(id, enterprise, account);
        return ResultJson.success("删除成功");
    }

    /**
     * 删除企业和关联信息
     * @param id
     * @param enterprise
     * @param account
     */
    private void delete(Integer id, Enterprise enterprise, Account account){
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("enterprise_id", id);
        organizationDao.delete(organizationQueryWrapper);

        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("enterprise_id", id);
        roleDao.delete(roleQueryWrapper);

        // 删除与app的关联关系
        QueryWrapper<EnterpriseApp> enterpriseAppQueryWrapper = new QueryWrapper<>();
        enterpriseAppQueryWrapper.eq("enterprise_id", id);
        enterpriseAppService.remove(enterpriseAppQueryWrapper);

        //删除企业扩展信息
        QueryWrapper<EnterpriseExtra> enterpriseExtraQueryWrapper = new QueryWrapper<>();
        enterpriseExtraQueryWrapper.eq("enterprise_id",id);
        enterpriseExtraService.remove(enterpriseExtraQueryWrapper);
        // 删除关联关系
        this.deleteRelation(id);

        //记录日志
        enterpriseLogRecord(account, LogOperationTypeEnum.DELETE, "删除企业" + "【" + enterprise.getName() + "】", enterprise.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson update(EnterpriseDTO enterpriseDTO, List<Integer> permissions, AbstractAccount account) {
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(enterpriseDTO, enterprise);
        // 企业类型
        if (!CollectionUtils.isEmpty(enterpriseDTO.getTypes())) {
            enterprise.setType(Joiner.on(",").join(enterpriseDTO.getTypes()));
        }
        // 参数处理校验
        ResultJson resultJson = saveCheck(enterprise);
        if (!resultJson.getState()) {
            return resultJson;
        }
        // 查询原有数据
        Enterprise enterpriseOld = enterpriseDao.selectById(enterprise.getId());
        enterpriseDTO.setIndustryId(enterpriseOld.getIndustryId());
        enterpriseDTO.setOrganizationId(enterpriseOld.getOrganizationId());

        List<Integer> permissionOld = getPermissionOld(enterprise.getId());
        enterpriseDao.updateById(enterprise);
        // 同步修改组织名称
        if (!enterprise.getName().equals(enterpriseOld.getName()) || !enterprise.getCode().equals(enterpriseOld.getCode())) {
            this.updateOrganization(enterprise);
        }
        // 是否更新权限信息
        if(enterpriseDTO.isUpdatePermission()){
            updatePermission(enterprise, enterpriseDTO, permissions, permissionOld);
        }
        // 更新企业管理员信息
        if (!StringUtils.isEmpty(enterpriseDTO.getAdminAccount().getLoginName())){
            CentDataVerifyUtil.loginNameVerify(enterpriseDTO.getAdminAccount().getLoginName());
        }
        updateManger(enterpriseDTO, account);
        //添加场景关系
        createSceneEnterprise(enterpriseDTO.getSceneIds(),enterprise.getId());
        // 保存入驻企业信息
        saveEnterpriseEnter(enterprise, enterpriseDTO);
        //保存企业扩展信息
        enterpriseExtraService.save(enterprise.getId(), enterpriseDTO.getExtra());
        // 非运营商企业
        if(!CollectionUtils.isEmpty(enterpriseDTO.getTypes()) && !enterpriseDTO.getTypes().contains(EnterpriseTypeEnum.OPERATOR.id.intValue())){
            projectService.bindProject(enterprise.getId(),enterpriseDTO.getAuthProjectIds(),true);
        }
        // 下发企业、权限信息
        sendTenantToMQ("update", enterprise, permissions);
        //记录日志
        enterpriseLogRecord(account, LogOperationTypeEnum.UPDATE, "编辑企业" + "【" + enterprise.getName() + "】", enterpriseOld.getId());
        return ResultJson.success("修改成功");
    }

    /**
     * 补充除当前业态以外的其他业态的权限
     * @param permissions
     * @param enterpriseDTO
     */
    private void addPermissionOthers(List<Integer> permissions, EnterpriseDTO enterpriseDTO) {
        QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
        enterprisePermissionQueryWrapper.eq("enterprise_id", enterpriseDTO.getId());
        List<EnterprisePermission> list = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
        List<Integer> collect = list.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList());
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.select("id");
        permissionQueryWrapper.in("id", collect);
        permissionQueryWrapper.ne("industry_id", enterpriseDTO.getUpdateCurrentIndustry());
        List<Permission> otherIndustryPermission = permissionDao.selectList(permissionQueryWrapper);
        List<Integer> otherIndustryPermissionId = otherIndustryPermission.stream().map(i -> i.getId()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(otherIndustryPermissionId)){
            permissions.addAll(otherIndustryPermissionId);
        }
    }

    /**
     * 获取原始权限
     * @param enterpriseId
     * @return
     */
    private List<Integer> getPermissionOld(Integer enterpriseId){
        QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
        enterprisePermissionQueryWrapper.eq("enterprise_id", enterpriseId);
        List<EnterprisePermission> enterprisePermissions = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
        return enterprisePermissions.stream().map(e -> e.getPermissionId()).collect(Collectors.toList());
    }

    /**
     * 需要移除的权限 项目权限 角色权限等
     * @param permissionOld
     * @param enterprise
     * @param permissions
     */
    private void toDelete(List<Integer> permissionOld, Enterprise enterprise, List<Integer> permissions){
        List<Integer> dels = new ArrayList<>();
        dels.addAll(permissionOld);
        // 需要删除的权限
        permissionOld.retainAll(permissions);
        dels.removeAll(permissionOld);
        if (!dels.isEmpty()) {
            dels = dels.stream().distinct().collect(Collectors.toList());
            deletePermission(dels, enterprise);
        }
    }

    /**
     * 更新与企业权限相关的 (先删后增)
     * @param enterprise
     * @param enterpriseDTO
     * @param permissions
     * @param permissionOld
     */
    private void updatePermission(Enterprise enterprise, EnterpriseDTO enterpriseDTO, List<Integer> permissions, List<Integer> permissionOld){
        // 保存企业与权限关系
        permissions = this.savePermissions(permissions, enterpriseDTO);
        // 查询角色
        Integer roleId = this.queryManagerRoleId(enterprise.getId());
        if (StringUtils.isEmpty(roleId)) {
            throw new BusinessException("未查询到企业管理员角色");
        }
        // 修改角色
        permissionFilter(permissions);
        rolePermissionService.createRolePermission(roleId, permissions);
        // 处理要删除的权限信息
        toDelete(permissionOld, enterprise, permissions);
        // 企业 app的关系
        QueryWrapper<EnterpriseApp> enterpriseAppQueryWrapper = new QueryWrapper<>();
        enterpriseAppQueryWrapper.eq("enterprise_id", enterprise.getId());
        enterpriseAppService.remove(enterpriseAppQueryWrapper);
        createEnterpriseApp(permissions, enterprise);
    }

    /**
     * 更新企业管理员信息
     *
     * 根据手机号判断如果是新手机号自动创建帐号
     * 如果是已存在的帐号给这个帐号增加企业管理员角色
     * 如果没有在这个企业下有企业员工信息则给他增加一条企业员工信息
     * @param enterpriseDTO
     */
    private void updateManger(EnterpriseDTO enterpriseDTO, AbstractAccount operator) {
        if (StringUtils.isEmpty(enterpriseDTO.getAdminAccount().getName())) {
            throw new DataException("缺少姓名");
        }
        if (StringUtils.isEmpty(enterpriseDTO.getAdminAccount().getPhone())) {
            throw new DataException("缺少管理员手机号");
        }


        // 查询企业管理员角色 企业下的内置角色就是企业管理员角色
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id","enterprise_id");
        // 企业超管
        roleQueryWrapper.eq("type", RoleTypeEnum.MANAGER);
        roleQueryWrapper.eq("enterprise_id", enterpriseDTO.getId());
        List<Role> roles = roleService.list(roleQueryWrapper);

        if(roles.isEmpty()){
            throw new DataException("缺少企业管理员");
        }
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("phone", enterpriseDTO.getAdminAccount().getPhone());
        accountQueryWrapper.eq("is_deleted", false);
        accountQueryWrapper.eq("develop_id", enterpriseDTO.getDevelopId());
        log.info("帐号查询参数 {}   {}", enterpriseDTO.getAdminAccount().getPhone(), enterpriseDTO.getDevelopId());
        Account one = accountService.getOne(accountQueryWrapper);
        log.info("查询结果 {}", one);
        // 移除其他帐号的企业管理员角色
        QueryWrapper<AccountRole> accountRoleQueryWrapper1 = new QueryWrapper<>();
        accountRoleQueryWrapper1.in("role_id", roles.stream().map(i -> i.getId()).collect(Collectors.toList()));
        accountRoleService.remove(accountRoleQueryWrapper1);
        // 移除其他帐号有企业管理员角色权限组的企业管理员角色
        QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
        // 一般只有一个
        permissionGroupQueryWrapper.like("role_ids", roles.get(0).getId());
        List<PermissionGroup> permissionGroups = permissionGroupDao.selectList(permissionGroupQueryWrapper);
        if(!permissionGroups.isEmpty()){
            List<Integer> removeIds = new ArrayList<>();
            // 过滤出当前有这个角色的权限组
            for (PermissionGroup permissionGroup : permissionGroups) {
                List<Integer> roleIds = Arrays.stream(permissionGroup.getRoleIds().split(",")).map(i -> Integer.valueOf(i)).collect(Collectors.toList());
                // 因为查询的时候用的是模糊查询，这里要保证确实包含这个角色
                if(roleIds.contains(roles.get(0).getId())){
                    removeIds.add(permissionGroup.getId());
                }
            }
            if(CollectionUtils.isNotEmpty(removeIds)){
                permissionGroupDao.deleteBatchIds(removeIds);
            }
        }
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.setEnterpriseId(enterpriseDTO.getId());
        List<Project> projects = projectService.list(projectQuery,null);
        if(null != one){
            bindAccountInfo(one, roles, enterpriseDTO,projects);
            enterpriseDTO.getAdminAccount().setId(one.getId());
        }else{
            // 新建帐号 绑定企业管理员角色
            enterpriseDTO.getAdminAccount().setIndustryId(enterpriseDTO.getIndustryId());
            createEnterpriseMangerAccount(enterpriseDTO, roles,projects);
        }
        // 创建企业管理员员工信息
        createStaff(enterpriseDTO.getAdminAccount(), enterpriseDTO);
    }

    /**
     * 关联绑定帐号
     * @param one
     * @param roles
     * @param projects
     */
    private void bindAccountInfo(Account one, List<Role> roles, EnterpriseDTO enterpriseDTO, List<Project> projects){
        // 绑定企业管理员角色+授权运营商所有项目
        bindEnterpriseManager(one, roles,projects.stream().map(Project::getId).collect(Collectors.toList()));
        // 关联企业组织
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", one.getId());
        accountOrganizationQueryWrapper.eq("enterprise_id", enterpriseDTO.getId());
        accountOrganizationQueryWrapper.eq("type", OrganizationTypeEnum.ENTERPRISE.id.intValue());
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        if(accountOrganizations.isEmpty()){
            AccountOrganization accountOrganization = new AccountOrganization();
            accountOrganization.setAccountId(one.getId());
            accountOrganization.setOrganizationId(enterpriseDTO.getOrganizationId());
            accountOrganization.setEnterpriseId(enterpriseDTO.getId());
            accountOrganization.setType(OrganizationTypeEnum.ENTERPRISE.id.intValue());
            accountOrganizationDao.insert(accountOrganization);
        }
    }

    /**
     * 绑定企业管理员角色+把企业管理员角色加到当前账号第一个权限组
     * @param one
     * @param roles
     * @param projects
     */
    private void bindEnterpriseManager(Account one, List<Role> roles, List<Integer> projects){
        List<Integer> collect1 = roles.stream().map(i -> i.getId()).collect(Collectors.toList());
        if(!collect1.isEmpty()){
            List<AccountRole> accountRoles = new ArrayList<>();
            for (Integer role : collect1) {
                AccountRole accountRole = new AccountRole();
                accountRole.setAccountId(one.getId());
                accountRole.setRoleId(role);
                accountRoles.add(accountRole);
            }
            accountRoleService.saveBatch(accountRoles);

            List<AccountProject> accountProjects = new ArrayList<>();
            for (Integer project : projects){
                AccountProject accountProject = new AccountProject();
                accountProject.setAccountId(one.getId());
                accountProject.setProjectId(project);
                accountProjects.add(accountProject);
            }
            accountProjectService.saveBatch(accountProjects);
            // 增加权限组
            QueryWrapper<PermissionGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id",one.getId());
            queryWrapper.eq("enterprise_id",roles.get(0).getEnterpriseId());
            queryWrapper.orderByAsc("created_at");
            List<PermissionGroup> permissionGroups = permissionGroupDao.selectList(queryWrapper);
            PermissionGroup permissionGroup = new PermissionGroup();
            if (!permissionGroups.isEmpty()){
                permissionGroup = permissionGroups.get(0);
                permissionGroup.setRoleIds(Joiner.on(",").join(collect1)+","+permissionGroup.getRoleIds());
                List<Integer> result = new ArrayList<>(projects);
                String[] split = permissionGroup.getProjectIds().split(",");
                for (String s : split) {
                    result.add(Integer.parseInt(s));
                }
                permissionGroup.setProjectIds(Joiner.on(",").join(result.stream().distinct().collect(Collectors.toList())));
                permissionGroupDao.updateById(permissionGroup);
            }else{
                permissionGroup.setAccountId(one.getId());
                permissionGroup.setRoleIds(Joiner.on(",").join(collect1));
                permissionGroup.setEnterpriseId(roles.get(0).getEnterpriseId());
                permissionGroup.setProjectIds(Joiner.on(",").join(projects));
                permissionGroupDao.insert(permissionGroup);
            }
        }
    }

    /**
     * 创建帐号关联企业管理员角色
     * @param enterpriseDTO
     * @param roles
     * @param projects
     */
    private void createEnterpriseMangerAccount(EnterpriseDTO enterpriseDTO, List<Role> roles, List<Project> projects){
        AccountDTO adminAccount = enterpriseDTO.getAdminAccount();
        if (StringUtils.isEmpty(adminAccount.getLoginName())) {
            String loginName = UUID.randomUUID().toString().replaceAll("-", "").substring(0,20);
            adminAccount.setLoginName(loginName);
        }else {
            CentDataVerifyUtil.loginNameVerify(adminAccount.getLoginName());
        }
        AccountRelation accountRelation = new AccountRelation();
        accountRelation.setEnterpriseIds(Arrays.asList(enterpriseDTO.getId()));
        accountRelation.setRoleIds(roles.stream().map(i -> i.getId()).collect(Collectors.toList()));
        List<PermissionGroupDTO> permissionGroupDTOS = new ArrayList<>();
        PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
        permissionGroupDTO.setRoleList(roles.stream().map(i -> i.getId()).collect(Collectors.toList()));
        permissionGroupDTO.setProjectList(projects.stream().map(Project::getId).collect(Collectors.toList()));
        permissionGroupDTOS.add(permissionGroupDTO);
        Account account = new Account();
        BeanUtils.copyProperties(adminAccount, account);
        accountService.createAccountV2(account, accountRelation, permissionGroupDTOS);
        adminAccount.setId(account.getId());
    }

    /**
     * 移除需要删除的权限
     *
     * @param dels
     * @param enterprise
     */
    private void deletePermission(List<Integer> dels, Enterprise enterprise) {
        //移除项目的权限
        //1)查询企业下的所有项目
        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
        projectQueryWrapper.select("id");
        projectQueryWrapper.eq("enterprise_id", enterprise.getId());
        projectQueryWrapper.eq("is_deleted", false);
        List<Project> projects = projectDao.selectList(projectQueryWrapper);
        //2)删除权限
        if (!projects.isEmpty()) {
            List<Integer> projectIds = projects.stream().map(p -> p.getId()).collect(Collectors.toList());
            QueryWrapper<ProjectPermission> projectPermissionQueryWrapper = new QueryWrapper<>();
            projectPermissionQueryWrapper.in("project_id", projectIds);
            projectPermissionQueryWrapper.in("permission_id", dels);
            projectPermissionService.remove(projectPermissionQueryWrapper);
        }

        //移除企业下所有角色权限
        //1）先查询企业下的所有角色
        QueryWrapper<Role> enterpriseChildRole = new QueryWrapper<>();
        enterpriseChildRole.select("id");
        enterpriseChildRole.eq("enterprise_id", enterprise.getId());
        List<Role> roles = roleDao.selectList(enterpriseChildRole);
        //2）移除权限
        if (!roles.isEmpty()) {
            List<Integer> roleIds = roles.stream().map(r -> r.getId()).collect(Collectors.toList());
            QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
            rolePermissionQueryWrapper.in("role_id", roleIds);
            rolePermissionQueryWrapper.in("permission_id", dels);
            rolePermissionService.remove(rolePermissionQueryWrapper);
        }
    }

    private void createEnterpriseApp(List<Integer> permissions, Enterprise enterprise) {
        if (CollectionUtils.isNotEmpty(permissions)) {
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.select("id", "app_id");
            permissionQueryWrapper.in("id", permissions);
            permissionQueryWrapper.eq("is_deleted", false);
            List<Permission> permissions1 = permissionDao.selectList(permissionQueryWrapper);

            Set<Integer> collect1 = permissions1.stream().map(i -> i.getAppId()).collect(Collectors.toSet());
            List<EnterpriseApp> enterpriseApps = new ArrayList<>(collect1.size());
            for (Integer i : collect1) {
                EnterpriseApp enterpriseApp = new EnterpriseApp();
                enterpriseApp.setAppId(i);
                enterpriseApp.setEnterpriseId(enterprise.getId());
                enterpriseApps.add(enterpriseApp);
            }
            // 添加企业和app的关联关系
            enterpriseAppService.saveBatch(enterpriseApps);
        }
    }

    private void permissionFilter(List<Integer> permissionIdList) {
        // 创建企业管理员角色需要过滤 新增企业的权限
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.select("id");
        permissionQueryWrapper.in("code", EXCLUDE_ENTERPRISE_PERMISSION);
        List<Permission> permissions = permissionDao.selectList(permissionQueryWrapper);
        if (!permissions.isEmpty()) {
            List<Integer> ids = permissions.stream().map(p -> p.getId()).collect(Collectors.toList());
            permissionIdList.removeAll(ids);
        }
    }

    @Override
    public Enterprise findById(Integer id) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
        enterpriseQueryWrapper.eq("id", id);
        enterpriseQueryWrapper.eq("is_deleted", false);
        return enterpriseDao.selectOne(enterpriseQueryWrapper);
    }

    @Override
    public ResultJson updateLogo(Integer id, String logo) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
        enterpriseQueryWrapper.eq("id", id);
        Enterprise enterprise = enterpriseDao.selectOne(enterpriseQueryWrapper);
        if (null == enterprise) {
            return ResultJson.fail("企业不存在");
        }
        enterprise.setLogo(logo);
        enterpriseDao.updateById(enterprise);
        //记录日志
        enterpriseLogRecord(null, LogOperationTypeEnum.UPDATE, "编辑企业" + "【" + enterprise.getName() + "】", enterprise.getId());
        return ResultJson.success();
    }


    @Override
    public Page<Enterprise> page(EnterpriseQuery enterpriseQuery, Page page, Account account) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = paramHandler(enterpriseQuery, account);
        enterpriseQueryWrapper.eq("is_deleted", false);
        return enterpriseDao.selectPage(page, enterpriseQueryWrapper);
    }

    @Override
    public Enterprise find(EnterpriseQuery enterpriseQuery, Account account) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = paramHandler(enterpriseQuery, account);
        enterpriseQueryWrapper.eq("is_deleted", false);
        List<Enterprise> enterprises = enterpriseDao.selectList(enterpriseQueryWrapper);
        if (enterprises.isEmpty()) {
            return null;
        } else if (1 == enterprises.size()) {
            return enterprises.get(0);
        } else {
            log.warn("查询一个但是返回了多个结果 {}", JSONObject.toJSONString(enterprises));
            return enterprises.get(0);
        }
    }


    @Override
    public List<Enterprise> list(EnterpriseQuery enterpriseQuery, Account account) {
        // 处理请求参数
        QueryWrapper<Enterprise> queryWrapper = paramHandler(enterpriseQuery, account);
        queryWrapper.eq("is_deleted", false);
        return enterpriseDao.selectList(queryWrapper);
    }


    @Override
    public List<Enterprise> list(EnterpriseQuery enterpriseQuery) {
        if (Objects.isNull(enterpriseQuery)) {
            return null;
        }
        // 处理请求参数
        LambdaQueryWrapper<Enterprise> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Enterprise::getIsDeleted, false);
        if (CollectionUtils.isNotEmpty(enterpriseQuery.getIdList())) {
            queryWrapper.in(Enterprise::getId, enterpriseQuery.getIdList());
        }
        return enterpriseDao.selectList(queryWrapper);
    }


    @Override
    public List<EnterpriseDTO> listDetail(EnterpriseQuery enterpriseQuery, Account account) {
        // 处理请求参数
        QueryWrapper<Enterprise> queryWrapper = paramHandler(enterpriseQuery, account);
        queryWrapper.eq("is_deleted", false);
        List<Enterprise> enterprises = enterpriseDao.selectList(queryWrapper);
//        List<EnterpriseDTO> enterpriseDTOS = new ArrayList<>();
//        for (Enterprise enterprise : enterprises){
//            EnterpriseDTO enterpriseDTO = detail(enterprise);
//            enterpriseDTOS.add(enterpriseDTO);
//        }
        return convertDetail(enterprises);
    }

    private List<EnterpriseDTO> convertDetail(List<Enterprise> enterprises){
        List<Integer> entIds = enterprises.stream().map(Enterprise::getId).collect(Collectors.toList());
        //查找企业扩展信息
        QueryWrapper<EnterpriseExtra> extraQueryWrapper = new QueryWrapper<>();
        extraQueryWrapper.in("enterprise_id",entIds);
        Map<Integer,String> extraMap = enterpriseExtraService.list(extraQueryWrapper).stream().collect(Collectors.toMap(EnterpriseExtra::getEnterpriseId,EnterpriseExtra::getJson));
        //查找企业管理员信息
        Map<Integer,Account> accountMap = enterpriseMangerMap(entIds);
        //查找租赁空间
        QueryWrapper<EnterpriseSpace> enterpriseSpaceQueryWrapper = new QueryWrapper<>();
        enterpriseSpaceQueryWrapper.in("enterprise_id", entIds);
        List<EnterpriseSpace> enterpriseSpaces = enterpriseSpaceService.list(enterpriseSpaceQueryWrapper);
        Map<Integer,List<Organization>> entSpaceMap = new HashMap<>();
        Map<Integer, String> chainNames = new HashMap<>();
        if (!enterpriseSpaces.isEmpty()){
            Map<Integer,List<Integer>> spaceIdMap = enterpriseSpaces.stream().collect(Collectors.groupingBy(EnterpriseSpace::getEnterpriseId,Collectors.mapping(EnterpriseSpace::getOrganizationId,Collectors.toList())));
            List<Integer> collect = enterpriseSpaces.stream().map(i -> i.getOrganizationId()).distinct().collect(Collectors.toList());
            List<Organization> organizations = organizationService.listByIds(collect);
            OrganizationQuery organizationQuery = new OrganizationQuery();
            organizationQuery.setIds(organizations.stream().map(Organization::getId).distinct().collect(Collectors.toList()));
            organizationQuery.setTypes(organizationTypeService.spaceIds());
            chainNames = organizationService.batchFullName(organizationQuery);
            for (Map.Entry<Integer, List<Integer>> integerListMap : spaceIdMap.entrySet()){
                List<Organization> organizationList = organizations.stream().filter(i -> integerListMap.getValue().contains(i.getId())).collect(Collectors.toList());
                entSpaceMap.put(integerListMap.getKey(),organizationList);
            }
        }
        //查找授权项目
        QueryWrapper<EnterpriseProject> enterpriseProjectQueryWrapper = new QueryWrapper<>();
        enterpriseProjectQueryWrapper.in("enterprise_id", entIds);
        List<EnterpriseProject> enterpriseProjects = enterpriseProjectService.list(enterpriseProjectQueryWrapper);
        Map<Integer,List<Project>> entProjectMap = new HashMap<>();
        if (!enterpriseProjects.isEmpty()){
            Map<Integer,List<Integer>> projectIdMap = enterpriseProjects.stream().collect(Collectors.groupingBy(EnterpriseProject::getEnterpriseId,Collectors.mapping(EnterpriseProject::getProjectId,Collectors.toList())));
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.select("id","name");
            projectQueryWrapper.in("id", enterpriseProjects.stream().map(EnterpriseProject::getProjectId).collect(Collectors.toList()));
            List<Project> projects = projectService.list(projectQueryWrapper);
            for (Map.Entry<Integer,List<Integer>> integerListEntry : projectIdMap.entrySet()){
                List<Project> projectList = projects.stream().filter(i -> integerListEntry.getValue().contains(i.getId())).collect(Collectors.toList());
                entProjectMap.put(integerListEntry.getKey(),projectList);
            }
        }
        Map<Integer,Integer> staffCount = getStaffCount(entIds);
        List<EnterpriseDTO> result = new ArrayList<>();
        for (Enterprise ent : enterprises){
            EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
            BeanUtils.copyProperties(ent, enterpriseDTO);
            //填充扩展信息
            if (null != extraMap.get(ent.getId())){
                JSONObject extra = JSONObject.parseObject(extraMap.get(ent.getId()));
                enterpriseDTO.setExtra(extra);
                //填充行业类型
                if (null != extra && extra.containsKey("cusIndustry")){
                    enterpriseDTO.setIndustryTypeName(extra.getJSONObject("customerInformation").getJSONObject("cusIndustry").getString("name"));
                }
            }
            enterpriseDTO.setRegion(getRegion(ent.getProvinceId(), ent.getCityId(), ent.getDistrictId()));
//            enterpriseMangerSetter(ent.getId(), enterpriseDTO);
            if(!com.xhwl.common.utils.StringUtils.isEmpty(ent.getType())){
                String[] split = ent.getType().split(",");
                enterpriseDTO.setTypes(Arrays.stream(split).map(i -> Integer.valueOf(i)).collect(Collectors.toList()));
            }
            // 回显租赁空间
            if(ent.getType().contains(EnterpriseTypeEnum.ENTER.id.toString())){
                List<Organization> organizationList = entSpaceMap.get(ent.getId());
                if (null != organizationList && !organizationList.isEmpty()){
                    List<EnterpriseRentVO> enterpriseRentVOS = processRentVO(organizationList,enterpriseSpaces,ent.getId());
                    enterpriseDTO.setEnterpriseRentVOS(enterpriseRentVOS);
                    StringBuilder chainName = new StringBuilder();
                    for (Map.Entry<Integer,String> integerStringEntry : chainNames.entrySet()){
                        List<Integer> spaceIds = organizationList.stream().map(Organization::getId).collect(Collectors.toList());
                        if (spaceIds.contains(integerStringEntry.getKey())){
                            chainName.append(integerStringEntry.getValue()).append(",");
                        }
                    }
                    enterpriseDTO.setSpacePosition(chainName.substring(0, chainName.length() - 1));
                }
            }
            //填充授权项目
            List<Project> projects = entProjectMap.get(ent.getId());
            if (null != projects && !projects.isEmpty()){
                enterpriseDTO.setAuthProjectIds(projects.stream().map(Project::getId).collect(Collectors.toList()));
                enterpriseDTO.setAuthProjectNames(projects.stream().map(Project::getName).collect(Collectors.toList()));
            }
            if (null != staffCount.get(ent.getId())){
                enterpriseDTO.setStaffCount((Integer) staffCount.get(ent.getId()));
            }
            if (null != accountMap.get(ent.getId())){
                AccountDTO accountDTO = new AccountDTO();
                BeanUtils.copyProperties(accountMap.get(ent.getId()), accountDTO);
                enterpriseDTO.setAdminAccount(accountDTO);
                enterpriseDTO.setManagers(Collections.singletonList(accountMap.get(ent.getId())));
            }
            result.add(enterpriseDTO);
        }
        return result;
    }

    @Override
    public Map<Integer, Integer> getStaffCount(List<Integer> entIds) {
        if (entIds.isEmpty()){
            return new HashMap<>();
        }
        List<Map<String,Integer>> staffCountList = enterpriseDao.getStaffCount(entIds);
        Map<Integer, Integer> staffCount = new HashMap<>();
        for (Map<String,Integer> integerIntegerMap : staffCountList){
            staffCount.put(integerIntegerMap.get("enterprise_id"), Integer.parseInt(String.valueOf(integerIntegerMap.get("count(*)"))));
        }
        return staffCount;
    }

    @Override
    public List<Enterprise> getAll() {
        QueryWrapper<Enterprise> entQueryWrapper = new QueryWrapper<>();
        entQueryWrapper.in("is_deleted", 0);
        List<Enterprise> ents = enterpriseDao.selectList(entQueryWrapper);
        return ents;
    }

    private EnterpriseDTO detail(Enterprise ent){
        EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
        BeanUtils.copyProperties(ent, enterpriseDTO);
        //查询企业扩展属性
        JSONObject extra = enterpriseExtraService.list(ent.getId());
        enterpriseDTO.setExtra(extra);
        //填充行业类型
        if (null != extra && extra.containsKey("cusIndustry")){
            enterpriseDTO.setIndustryTypeName(extra.getJSONObject("customerInformation").getJSONObject("cusIndustry").getString("name"));
        }
        enterpriseDTO.setRegion(getRegion(ent.getProvinceId(), ent.getCityId(), ent.getDistrictId()));
        // 回显企业管理员
        enterpriseMangerSetter(ent.getId(), enterpriseDTO);
//        enterprisePermissionSetter(ent.getId(), enterpriseDTO);
        // 企业类型
        if(!com.xhwl.common.utils.StringUtils.isEmpty(ent.getType())){
            String[] split = ent.getType().split(",");
            enterpriseDTO.setTypes(Arrays.stream(split).map(i -> Integer.valueOf(i)).collect(Collectors.toList()));
        }
        // 回显租赁空间
        if(ent.getType().contains(EnterpriseTypeEnum.ENTER.id.toString())){
            rentSpaceSetter(ent, enterpriseDTO);
        }
        projectInfoSetter(ent.getId(), enterpriseDTO);
        //填充员工数量
        staffCountSeter(ent.getId(),enterpriseDTO);
        return enterpriseDTO;
    }

    private void staffCountSeter(Integer id, EnterpriseDTO enterpriseDTO) {
        Map staffCount = staffService.findByEnterpriseIdList(Collections.singletonList(id));
        enterpriseDTO.setStaffCount((Integer) staffCount.get(id));
    }

    public String getRegion(Integer provincesId, Integer cityId, Integer districtId) {
        List<Integer> integers = Arrays.asList(provincesId, cityId, districtId);
        List<Region> regions = regionService.findByIds(integers);
        if (regions.isEmpty()) {
            return null;
        }
        Map<Integer, String> reMap = regions.stream().collect(Collectors.toMap(Region::getId, Region::getName));
        StringBuilder sbd = new StringBuilder();
        if (null != provincesId && com.xhwl.common.utils.StringUtils.isNotEmpty(reMap.get(provincesId))) {
            sbd.append(reMap.get(provincesId));
        }
        if (null != cityId && com.xhwl.common.utils.StringUtils.isNotEmpty(reMap.get(cityId))) {
            sbd.append(reMap.get(cityId));
        }
        if (null != districtId && com.xhwl.common.utils.StringUtils.isNotEmpty(reMap.get(districtId))) {
            sbd.append(reMap.get(districtId));
        }
        return sbd.toString();
    }
    /**
     * 填充企业管理员
     * @param id
     * @param enterpriseDTO
     */
    public void enterpriseMangerSetter(Integer id, EnterpriseDTO enterpriseDTO){
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id");
        roleQueryWrapper.eq("is_initialized", true);
        roleQueryWrapper.eq("enterprise_id", id);
        roleQueryWrapper.eq("is_deleted", false);
        roleQueryWrapper.eq("type", RoleTypeEnum.MANAGER.code);
        List<Role> list = roleService.list(roleQueryWrapper);
        if(!list.isEmpty()){
            QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
            accountRoleQueryWrapper.in("role_id", list.stream().map(i -> i.getId()).collect(Collectors.toList()));
            List<AccountRole> list1 = accountRoleService.list(accountRoleQueryWrapper);
            if(!list1.isEmpty()){
                QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
                accountQueryWrapper.select("id", "name", "login_name", "phone");
                accountQueryWrapper.eq("is_deleted", false);
                accountQueryWrapper.in("id", list1.stream().map(i -> i.getAccountId()).collect(Collectors.toList()));
                List<Account> list2 = accountService.list(accountQueryWrapper);
                if(!org.springframework.util.CollectionUtils.isEmpty(list2)){
                    enterpriseDTO.setManagers(list2);
                    Account account = list2.get(0);
                    AccountDTO accountDTO = new AccountDTO();
                    BeanUtils.copyProperties(account, accountDTO);
                    enterpriseDTO.setAdminAccount(accountDTO);
                }else{
                    log.warn("企业管理员帐号不存在");
                }

            }else{
                log.info("没有企业管理员帐号");
            }
        }else{
            log.warn("当前企业 {} 没有企业管理员角色", id);
        }
    }

    private Map<Integer,Account> enterpriseMangerMap(List<Integer> entIds){
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id","enterprise_id");
        roleQueryWrapper.eq("is_initialized", true);
        roleQueryWrapper.in("enterprise_id", entIds);
        roleQueryWrapper.eq("is_deleted", false);
        roleQueryWrapper.eq("type", RoleTypeEnum.MANAGER.code);
        List<Role> list = roleService.list(roleQueryWrapper);
        Map<Integer,Account> entMangerMap = new HashMap<>();
        if(!list.isEmpty()) {
            Map<Integer,List<Integer>> entRoleMap = list.stream().filter(i -> null != i.getEnterpriseId()).collect(Collectors.groupingBy(Role::getEnterpriseId,Collectors.mapping(Role::getId,Collectors.toList())));
            QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
            accountRoleQueryWrapper.in("role_id", list.stream().map(i -> i.getId()).collect(Collectors.toList()));
            List<AccountRole> list1 = accountRoleService.list(accountRoleQueryWrapper);
            Map<Integer,List<Integer>> entAccountMap = new HashMap<>();
            for (Map.Entry<Integer,List<Integer>> integerListEntry : entRoleMap.entrySet()){
                List<AccountRole> accountRoles = list1.stream().filter(i ->integerListEntry.getValue().contains(i.getRoleId())).collect(Collectors.toList());
                entAccountMap.put(integerListEntry.getKey(),accountRoles.stream().map(AccountRole::getAccountId).collect(Collectors.toList()));
            }
            if (!list1.isEmpty()) {
                QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
                accountQueryWrapper.select("id", "name", "login_name", "phone");
                accountQueryWrapper.eq("is_deleted", false);
                accountQueryWrapper.in("id", list1.stream().map(i -> i.getAccountId()).collect(Collectors.toList()));
                List<Account> list2 = accountService.list(accountQueryWrapper);
                for (Map.Entry<Integer,List<Integer>> integerListEntry : entAccountMap.entrySet()){
                    List<Account> accounts = list2.stream().filter(i -> integerListEntry.getValue().contains(i.getId())).collect(Collectors.toList());
                    if (!accounts.isEmpty()){
                        entMangerMap.put(integerListEntry.getKey(),accounts.get(0));
                    }
                }
            }
        }
        return entMangerMap;
    }
    /**
     * 回显企业权限
     * @param id
     * @param enterpriseDTO
     */
    public void enterprisePermissionSetter(Integer id, EnterpriseDTO enterpriseDTO){
        List<Permission> permissionList = permissionService.getListByEnterpriseId(null, id);
        if (null != permissionList && !permissionList.isEmpty()) {
            List<Integer> permissionIds = permissionList.stream().filter(p -> p.getMenuType() != 0).map(Permission::getId).collect(Collectors.toList());
            log.info("permission size {}", permissionIds.size());
            enterpriseDTO.setPermissions(permissionIds);
            // 回显企业权限树
            PermissionTreeDTO permissionTreeDTO = new PermissionTreeDTO();
            permissionTreeDTO.setIds(permissionIds);
            enterpriseDTO.setPermissionTree(permissionService.getPermissionTree(permissionTreeDTO));
        }
    }
    /**
     * 填充租赁空间
     * @param ent
     * @param enterpriseDTO
     */
    private void rentSpaceSetter(Enterprise ent, EnterpriseDTO enterpriseDTO){
        QueryWrapper<EnterpriseSpace> enterpriseSpaceQueryWrapper = new QueryWrapper<>();
        enterpriseSpaceQueryWrapper.eq("enterprise_id", ent.getId());
        List<EnterpriseSpace> list1 = enterpriseSpaceService.list(enterpriseSpaceQueryWrapper);
        if(!org.springframework.util.CollectionUtils.isEmpty(list1)){
            List<Integer> collect = list1.stream().map(i -> i.getOrganizationId()).distinct().collect(Collectors.toList());
            List<Organization> organizations = organizationService.listByIds(collect);
            if (CollectionUtils.isEmpty(organizations)){
                return;
            }
            //填充空间位置
            OrganizationQuery organizationQuery = new OrganizationQuery();
            organizationQuery.setIds(organizations.stream().map(Organization::getId).distinct().collect(Collectors.toList()));
            organizationQuery.setTypes(organizationTypeService.spaceIds());
            Map<Integer, String> chainNames = organizationService.batchFullName(organizationQuery);
            StringBuilder chainName = new StringBuilder();
            for (Map.Entry<Integer,String> integerStringEntry : chainNames.entrySet()){
                chainName.append(integerStringEntry.getValue()).append(",");
            }
            enterpriseDTO.setSpacePosition(chainName.toString());
            List<EnterpriseRentVO> list2 = processRentVO(organizations,list1,ent.getId());
            enterpriseDTO.setEnterpriseRentVOS(list2);
        }
    }

    private List<EnterpriseRentVO> processRentVO(List<Organization> organizations,List<EnterpriseSpace> spaces,Integer entId){
        Map<Integer, List<Organization>> collect1 = organizations.stream().collect(Collectors.groupingBy(Organization::getProjectId, Collectors.toList()));
        List<Integer> collect4 = organizations.stream().map(i -> i.getProjectId()).distinct().collect(Collectors.toList());
        List<Project> projects = projectService.listByIds(collect4);
        Map<Integer,Integer> countMap = projectService.projectCount(projects);
        Map<Integer,Project> projectMap = projects.stream().collect(Collectors.toMap(Project::getId, Function.identity()));
        List<EnterpriseRentVO> list2 = new ArrayList<>(collect1.size());
        for (Map.Entry<Integer, List<Organization>> integerListEntry : collect1.entrySet()) {
            EnterpriseRentVO enterpriseRentVO = new EnterpriseRentVO();
            enterpriseRentVO.setProjectId(integerListEntry.getKey());
            enterpriseRentVO.setProjectName(projectMap.get(integerListEntry.getKey()).getName());
//            enterpriseRentVO.setProjectStaffCount(countMap.get(integerListEntry.getKey()));
//            enterpriseRentVO.setProjectBuildingArea(projectMap.get(integerListEntry.getKey()).getBuildingArea());
            List<Integer> collect2 = integerListEntry.getValue().stream().map(i -> i.getId()).collect(Collectors.toList());
            List<String> collect3 = integerListEntry.getValue().stream().map(i -> i.getName()).collect(Collectors.toList());
            List<EnterpriseSpace> enterpriseSpaces = spaces.stream().filter(i -> collect2.contains(i.getOrganizationId()) && i.getEnterpriseId().equals(entId)).collect(Collectors.toList());
            enterpriseRentVO.setSpaceIds(collect2);
            enterpriseRentVO.setSpaceName(collect3);
            enterpriseRentVO.setRentStartTime(enterpriseSpaces.get(0).getRentStartTime());
            enterpriseRentVO.setRentEndTime(enterpriseSpaces.get(0).getRentEndTime());
            list2.add(enterpriseRentVO);
        }
        return list2;
    }
    /**
     * 填充项目相关
     * @param id
     * @param enterpriseDTO
     */
    public void projectInfoSetter(Integer id, EnterpriseDTO enterpriseDTO){
        // 回显项目权限
        projectPermissionSetter(id, enterpriseDTO);
        // 回显授权项目
        authProjectSetter(id, enterpriseDTO);
    }

    /**
     * 项目授权填充
     * @param id
     * @param enterpriseDTO
     */
    public void projectPermissionSetter(Integer id, EnterpriseDTO enterpriseDTO){
        QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
        enterprisePermissionQueryWrapper.eq("enterprise_id", id);
        enterprisePermissionQueryWrapper.isNotNull("project_id");
        List<EnterprisePermission> list2 = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
        if(!list2.isEmpty()){
            Map<Integer, List<Integer>> collect = list2.stream().collect(Collectors.groupingBy(EnterprisePermission::getProjectId, Collectors.mapping(EnterprisePermission::getPermissionId, Collectors.toList())));
            List<ProjectPermissionVO> projectPermissionVOS = new ArrayList<>(collect.size());
            for (Map.Entry<Integer, List<Integer>> entry : collect.entrySet()) {
                ProjectPermissionVO projectPermissionVO = new ProjectPermissionVO();
                projectPermissionVO.setProjectId(entry.getKey());
                projectPermissionVO.setPermissionIds(entry.getValue());
                projectPermissionVOS.add(projectPermissionVO);
            }
            enterpriseDTO.setProjectPermissionVOS(projectPermissionVOS);
        }
    }

    /**
     * 项目授权填充
     * @param id
     * @param enterpriseDTO
     */
    public void authProjectSetter(Integer id, EnterpriseDTO enterpriseDTO){
        QueryWrapper<EnterpriseProject> enterpriseProjectQueryWrapper = new QueryWrapper<>();
        enterpriseProjectQueryWrapper.eq("enterprise_id", id);
        List<EnterpriseProject> list3 = enterpriseProjectService.list(enterpriseProjectQueryWrapper);
        if(!list3.isEmpty()){
            List<Integer> collect = list3.stream().map(i -> i.getProjectId()).collect(Collectors.toList());
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.select("name");
            projectQueryWrapper.in("id", collect);
            List<Project> list4 = projectService.list(projectQueryWrapper);
            enterpriseDTO.setAuthProjectIds(collect);
            enterpriseDTO.setAuthProjectNames(list4.stream().map(i -> i.getName()).collect(Collectors.toList()));
        }
    }

    @Override
    public ResultJson setBan(AbstractAccount account, Integer id, Boolean isBan) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
        enterpriseQueryWrapper.eq("is_deleted", false);
        enterpriseQueryWrapper.eq("id", id);
        Enterprise enterprise = enterpriseDao.selectOne(enterpriseQueryWrapper);
        if (null == enterprise) {
            return ResultJson.fail("企业不存在");
        }
        enterprise.setStatus(isBan ? (short) 0 : (short) 1);
        enterpriseDao.updateById(enterprise);

        //记录日志
        StringBuilder sbd = new StringBuilder();
        sbd.append(isBan ? "禁用" : "启用").append("企业管理：").append(enterprise.getName()).append("企业");
        enterpriseLogRecord(account, isBan ? LogOperationTypeEnum.BAN : LogOperationTypeEnum.ACTIVE, sbd.toString(), id);
        return ResultJson.success();
    }

    @Override
    public List<Enterprise> findByAccount(Account operateAccount) {
        if (null == operateAccount || null == operateAccount.getId()) {
            log.info("帐号信息为空");
            return Collections.emptyList();
        }
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", operateAccount.getId());
        accountOrganizationQueryWrapper.eq("type", OrganizationTypeEnum.ENTERPRISE.id);
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        if (CollectionUtils.isEmpty(accountOrganizations)) {
            log.warn("帐号 {} 暂未关联企业信息", operateAccount.getId());
            return Collections.emptyList();
        }
        List<Integer> collect = accountOrganizations.stream().map(i -> i.getEnterpriseId()).distinct().collect(Collectors.toList());
        return enterpriseDao.selectBatchIds(collect);
    }

    @Override
    public List<Enterprise> listById(Integer enterpriseId, List<Integer> types) {
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted",false);
        queryWrapper.and(wrapper -> wrapper.in("id", enterpriseId).or().in("parent_id", enterpriseId));
        queryWrapper.in("type",types);
        return enterpriseDao.selectList(queryWrapper);
    }

    @Override
    public Map countResidentEntStaffs(Integer enterpriseId) {
        List<Integer> types = new ArrayList<>();
        types.add(2);
        List<Enterprise> enterprises = listById(enterpriseId, types);
        if (enterprises == null){
            return Collections.EMPTY_MAP;
        }
        List<Integer> enterpriseList = enterprises.stream().map(Enterprise::getId).distinct().collect(Collectors.toList());
        Map staffNumberMap = staffService.findByEnterpriseIdList(enterpriseList);
        return staffNumberMap;
    }

    @Override
    public ResultJson tree(Integer enterpriseId, List<Integer> types) {
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted",false);
        queryWrapper.and(wrapper -> wrapper.in("id", enterpriseId).or().in("parent_id", enterpriseId));
        queryWrapper.in("type",types);
        List<Enterprise> enterprises = enterpriseDao.selectList(queryWrapper);
        if (enterprises.isEmpty()){
            return ResultJson.success();
        }
        List<EnterpriseTreeDTO> enterpriseTreeDTOS = new ArrayList<>();
        Map<String,List<Enterprise>> map = enterprises.stream().collect(Collectors.groupingBy(Enterprise::getType));
        for (List<Enterprise> enterprises1 : map.values()){
            EnterpriseTreeDTO enterpriseTreeDTO = new EnterpriseTreeDTO();
            enterpriseTreeDTO.setHasChild(true);
            String type = enterprises1.get(0).getType();
            enterpriseTreeDTO.setType(type);
            if (type.equals(EnterpriseTypeEnum.SERVICE.id.toString())){
                enterpriseTreeDTO.setName("服务商");
            }else {
                enterpriseTreeDTO.setName("入驻商");
            }
            List<EnterpriseTreeDTO> enterpriseTreeDTOS1 = new ArrayList<>();
            for (Enterprise enterprise : enterprises1){
                EnterpriseTreeDTO enterpriseTreeDTO1 = new EnterpriseTreeDTO();
                enterpriseTreeDTO1.setId(enterprise.getId());
                enterpriseTreeDTO1.setName(enterprise.getName());
                enterpriseTreeDTO1.setHasChild(false);
                enterpriseTreeDTO1.setType(enterprise.getType());
                enterpriseTreeDTOS1.add(enterpriseTreeDTO1);
            }
            enterpriseTreeDTO.setChildren(enterpriseTreeDTOS1);
            enterpriseTreeDTOS.add(enterpriseTreeDTO);
        }
        return ResultJson.success(enterpriseTreeDTOS);
    }

    @Override
    public EnterpriseDTO getDetail(EnterpriseQuery enterpriseQuery) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = paramHandler(enterpriseQuery, null);
        Enterprise enterprise = enterpriseDao.selectOne(enterpriseQueryWrapper);
        if (null != enterprise) {
            EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
            BeanUtils.copyProperties(enterprise, enterpriseDTO);
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.in("enterprise_id", enterprise.getId());
            roleQueryWrapper.eq("type", RoleTypeEnum.MANAGER.code);
            roleQueryWrapper.eq("is_initialized", true);
            roleQueryWrapper.eq("is_deleted", false);
            List<Role> list = roleService.list(roleQueryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                Map<Integer, Integer> roleEnterpriseMap = list.stream().collect(Collectors.toMap(Role::getId, Role::getEnterpriseId));
                // 查询企业管理员帐号
                Map<Integer, List<Account>> roleAccountMap = accountService.getByRoleIds(list.stream().map(i -> i.getId()).collect(Collectors.toList()));
                Map<Integer, AccountDTO> accountDTOMap = new HashMap<>(roleAccountMap.size());
                for (Map.Entry<Integer, List<Account>> integerListEntry : roleAccountMap.entrySet()) {
                    List<Account> value = integerListEntry.getValue();
                    if (org.springframework.util.CollectionUtils.isEmpty(value)) {
                        continue;
                    }
                    Account account = value.get(0);
                    if(null == account) {
                        continue;
                    }
                    AccountDTO accountDTO = new AccountDTO();
                    accountDTO.setId(account.getId());
                    accountDTO.setName(account.getName());
                    accountDTO.setPhone(account.getPhone());
                    accountDTOMap.put(roleEnterpriseMap.get(integerListEntry.getKey()), accountDTO);
                }
                enterpriseDTO = detail(enterprise);
                return enterpriseDTO;
            }
        }
        return null;
    }

    @Override
    public Enterprise getOne(Integer id, Account account) {

        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", false);
        queryWrapper.eq("id", id);
        EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
        enterpriseQuery.setId(id);
        authHandler(queryWrapper, account, enterpriseQuery);
        return enterpriseDao.selectOne(queryWrapper);
    }

    /**
     * 过滤当前帐号所能查看的企业
     * @param queryWrapper
     * @param account
     * @param enterpriseQuery
     */
    private void authHandler(QueryWrapper<Enterprise> queryWrapper, Account account, EnterpriseQuery enterpriseQuery) {
        if (accountIsEmpty(account)) {
            // 查询账号的身份
            RoleTypeDTO roleTypeDTO = roleService.getAccountRoleType(account.getId());
            RoleTypeEnum roleTypeEnum = roleTypeDTO.getRoleTypeEnum();

            // 企业超管
            if(RoleTypeEnum.ENT_MANAGER.equals(roleTypeEnum)){
                // 企业管理员：管理企业（包含下级企业）
                queryWrapper.and(wrapper -> wrapper.in("id", roleTypeDTO.getEnterpriseIdList()).or().in("parent_id", roleTypeDTO.getEnterpriseIdList()).or().in("id", directRelated(account)));
            } else {
                // 普通帐号查询
                commonAccountQuery(queryWrapper, account, enterpriseQuery);
            }
        }
    }

    private static boolean accountIsEmpty(Account account){
        return account != null && !StringUtils.isEmpty(account.getId());
    }

    @Override
    public ResultJson deleteAdmin(Integer id, Account account) {
        Enterprise enterprise = enterpriseDao.selectById(id);
        if (null == enterprise) {
            return ResultJson.fail("企业不存在");
        }
        enterprise.setIsDeleted(true);
        int i = enterpriseDao.updateById(enterprise);
        if (0 == i) {
            return ResultJson.fail("数据错误");
        }
        delete(id, enterprise, account);
        return ResultJson.success("删除成功");
    }

    @Override
    public Boolean isOperator(Integer enterpriseId) {
        Enterprise enterprise = getById(enterpriseId);
        String[] split = enterprise.getType().split(",");
        List<String> types = Arrays.asList(split);
        return types.contains(EnterpriseTypeEnum.OPERATOR.id.toString());
    }

    @Override
    public Map<String, Integer> statisticsEnt(List<Integer> types) {
        Map<String, Integer> map = new HashMap<>();
        Integer all = enterpriseDao.selectCount(new QueryWrapper<Enterprise>().eq("is_deleted", 0).eq("status", 1));
        map.put("total", all);
        if (!CollectionUtils.isEmpty(types)) {
            for (Integer type : types) {
                Integer num = enterpriseDao.selectCount(new QueryWrapper<Enterprise>().eq("is_deleted", 0).eq("status", 1).like("type", type));
                map.put(type.toString(), num);
            }
        }
        return map;
    }

    /**
     * 保存企业与权限关系
     *
     * @param permissionIdList
     * @param enterpriseDTO
     */
    private List<Integer> savePermissions(List<Integer> permissionIdList, EnterpriseDTO enterpriseDTO) {
        List<ProjectPermissionVO> projectPermissionVOS = enterpriseDTO.getProjectPermissionVOS();
        if(!CollectionUtils.isEmpty(projectPermissionVOS)){
            for (ProjectPermissionVO projectPermissionVO : projectPermissionVOS) {
                if(CollectionUtils.isNotEmpty(projectPermissionVO.getPermissionIds())){
                    permissionIdList.addAll(projectPermissionVO.getPermissionIds());
                }
            }
        }
        permissionIdList = permissionIdList.stream().distinct().collect(Collectors.toList());
        // 企业管理员权限树只展示菜单，故默认添加菜单下按钮
        List<Integer> buttonPermissionIdList = permissionService.findButtonIdByMenuId(permissionIdList);
        if (!CollectionUtils.isEmpty(buttonPermissionIdList)) {
            permissionIdList.addAll(buttonPermissionIdList);
        }
        enterprisePermissionService.saveV2(enterpriseDTO, permissionIdList);
        return permissionIdList;
    }

    /**
     * 创建企业对应组织
     *
     * @param enterprise
     * @param account
     * @return
     */
    private void createOrganization(Enterprise enterprise, Account account) {
        Organization organization = new Organization();
        organization.setEnterpriseId(enterprise.getId());
        organization.setName(enterprise.getName());
        organization.setCode(enterprise.getCode());
        organization.setLevel(1);
        organization.setParentId(0);
        organization.setIndustryId(enterprise.getIndustryId());
        organization.setType(OrganizationTypeEnum.ENTERPRISE.id.intValue());
        organizationService.create(organization);
        enterprise.setOrganizationId(organization.getId());
    }

    /**
     * 更新企业对应组织
     *
     * @param enterprise
     */
    private void updateOrganization(Enterprise enterprise) {
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("enterprise_id", enterprise.getId());
        organizationQueryWrapper.eq("level", 1);
        List<Organization> organizations = organizationDao.selectList(organizationQueryWrapper);

        Organization organization = new Organization();
        organization.setId(organizations.get(0).getId());
        organization.setName(enterprise.getName());
        organization.setCode(enterprise.getCode());
        organizationDao.updateById(organization);
        organizationLogRecord(null, LogOperationTypeEnum.UPDATE, "编辑组织" + "【" + organization.getName() + "】", organization);
    }

    /**
     * 创建企业管理员角色
     *
     * @param enterprise
     * @param permissionIdList
     * @return
     */
    private Integer createManagerRole(Enterprise enterprise, List<Integer> permissionIdList) {

        // 创建企业管理员角色需要过滤 新增企业的权限
        permissionFilter(permissionIdList);

        RoleGrantDTO roleGrantDTO = new RoleGrantDTO();
//        roleGrantDTO.setIndustryId(enterprise.getIndustryId());
        roleGrantDTO.setEnterpriseId(enterprise.getId());
        roleGrantDTO.setName(RoleTypeEnum.ENT_MANAGER.name);
        roleGrantDTO.setGrade(BusinessType.ENTERPRISE.code);
        roleGrantDTO.setType(RoleTypeEnum.MANAGER.code);
        roleGrantDTO.setIsInitialized(true);
        roleGrantDTO.setLevel(1);
        roleGrantDTO.setSortNum(1);
        roleGrantDTO.setParentId(0);
        roleGrantDTO.setOrganizationId(enterprise.getOrganizationId());
        roleGrantDTO.setPermissionIds(permissionIdList);
        ResultJson<Integer> role = roleService.createRole(roleGrantDTO);
        return role.getResult();
    }

    /**
     * 查询企业管理员角色id
     *
     * @param enterpriseId
     * @return
     */
    private Integer queryManagerRoleId(Integer enterpriseId) {

        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setEnterpriseIdList(Arrays.asList(enterpriseId));
        roleQuery.setGrade(BusinessType.ENTERPRISE.code);
        roleQuery.setType(RoleTypeEnum.MANAGER.code);

        List<Role> roles = roleService.getRoleList(null, roleQuery);
        if (CollectionUtils.isEmpty(roles)) {
            return null;
        }
        return roles.get(0).getId();
    }

    /**
     * 创建企管账号
     *
     * @param industryId
     * @param enterpriseId
     * @param accountDTO
     */
    private Integer createManagerAccount(Short industryId, Integer enterpriseId, AccountDTO accountDTO) {
        Integer roleId = queryManagerRoleId(enterpriseId);
        Account account = new Account();
        account.setLoginName(accountDTO.getLoginName());
        account.setPassword(accountDTO.getPassword());
        account.setPhone(accountDTO.getPhone());
        account.setIndustryId(industryId);
        account.setName(accountDTO.getName());
        ResultJson<Integer> resultJson = accountService.createAccountAdmin(account, Arrays.asList(enterpriseId), null, Arrays.asList(roleId));
        return resultJson.getResult();
    }

    /**
     * 根据帐号过滤企业查询参数
     * @param queryWrapper
     * @param account
     * @param enterpriseQuery
     */
    private void headHandler(QueryWrapper<Enterprise> queryWrapper, Account account, EnterpriseQuery enterpriseQuery) {
        // 账号管理企业
        if (accountIsEmpty(account)) {
            // 查询账号的身份
            RoleTypeDTO roleTypeDTO = roleService.getAccountRoleType(account.getId());
            RoleTypeEnum roleTypeEnum = roleTypeDTO.getRoleTypeEnum();

            // 企业超管
            if(RoleTypeEnum.ENT_MANAGER.equals(roleTypeEnum)){
                // 判断是否是当前企业的超管
                if(null != enterpriseQuery && !CollectionUtils.isEmpty(enterpriseQuery.getIdList())){
                    // 当前企业的企业管理员
                    if(roleTypeDTO.getEnterpriseIdList().contains(enterpriseQuery.getIdList().get(0))){
                        // 企管查询
                        if(null != enterpriseQuery && null != enterpriseQuery.getShowChild() && enterpriseQuery.getShowChild()){
                            // 企业管理员：管理企业（包含下级企业）
                            queryWrapper.and(wrapper -> wrapper.in("id", roleTypeDTO.getEnterpriseIdList()).or().in("parent_id", roleTypeDTO.getEnterpriseIdList()));
                        }else{
                            // 普通帐号查询
                            queryWrapper.in("id", directRelated(account));
                        }
                    }else{
                        // 普通帐号查询
                        commonAccountQuery(queryWrapper, account, enterpriseQuery);
                    }
                }else{
                    List<Integer> enterpriseIds = new ArrayList<>();
                    // 关联的企业
                    List<Integer> acEntIds = directRelated(account);
                    if(!acEntIds.isEmpty()){
                        enterpriseIds.addAll(acEntIds);
                    }
                    enterpriseIds.addAll(roleTypeDTO.getEnterpriseIdList());
                    queryWrapper.in("id", enterpriseIds);
                }
            } else {
                // 普通帐号查询
                commonAccountQuery(queryWrapper, account, enterpriseQuery);
            }
        }
    }

    /**
     * 获取帐号直接关联的企业
     * @param account
     * @return
     */
    private List<Integer> directRelated(Account account){
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", account.getId());
        accountOrganizationQueryWrapper.eq("type", 1);
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        return accountOrganizations.stream().map(a -> a.getEnterpriseId()).distinct().collect(Collectors.toList());
    }

    /**
     * 处理请求参数
     *
     * @param enterpriseQuery
     * @param account
     */
    private QueryWrapper<Enterprise> paramHandler(EnterpriseQuery enterpriseQuery, Account account) {

        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        headHandler(queryWrapper, account, enterpriseQuery);
        if (null != enterpriseQuery) {
            if (!CollectionUtils.isEmpty(enterpriseQuery.getIdList())) {
                if(null != enterpriseQuery && null != enterpriseQuery.getShowChild() && enterpriseQuery.getShowChild()){
                    queryWrapper.and(wrapper -> wrapper.in("id", enterpriseQuery.getIdList()).or().in("parent_id", enterpriseQuery.getIdList()));
                }else{
                    queryWrapper.in("id", enterpriseQuery.getIdList());
                }
            }
            if (null != enterpriseQuery.getIndustryIdList() && 0 < enterpriseQuery.getIndustryIdList().size()) {
                queryWrapper.in("industry_id", enterpriseQuery.getIndustryIdList());
            }
            if (!StringUtils.isEmpty(enterpriseQuery.getName())) {
                queryWrapper.eq("name", enterpriseQuery.getName());
            }
            if (null != enterpriseQuery.getExcludeId()) {
                queryWrapper.ne("id", enterpriseQuery.getExcludeId());
            }
            if (!StringUtils.isEmpty(enterpriseQuery.getKeywords())) {
                queryWrapper.and(i -> i.like("name", enterpriseQuery.getKeywords()).or().like("code",enterpriseQuery.getKeywords()));
            }
            if (null != enterpriseQuery.getParentId()) {
                queryWrapper.eq("parent_id", enterpriseQuery.getParentId());
            }
            if (null != enterpriseQuery.getType()) {
                // 10个类型以上需要更换查询方式，目前只有3个
                queryWrapper.like("type", enterpriseQuery.getType());
            }
            //根据项目查找企业
            if (null != enterpriseQuery.getProjectId()){
                QueryWrapper<EnterpriseProject> projectQueryWrapper = new QueryWrapper<>();
                projectQueryWrapper.eq("project_id",enterpriseQuery.getProjectId());
                List<EnterpriseProject> enterpriseProjects = enterpriseProjectService.list(projectQueryWrapper);
                if (!enterpriseProjects.isEmpty()){
                    List<Integer> enterpriseIds = enterpriseProjects.stream().map(EnterpriseProject::getEnterpriseId).collect(Collectors.toList());
                    queryWrapper.in("id",enterpriseIds);
                }
            }
            if (null != enterpriseQuery.getStartTime() && null != enterpriseQuery.getEndTime() && null != enterpriseQuery.getIsCreateAt()){
                if (enterpriseQuery.getIsCreateAt()){
                    queryWrapper.ge("created_at",enterpriseQuery.getStartTime());
                    queryWrapper.le("created_at",enterpriseQuery.getEndTime());
                }else {
                    queryWrapper.ge("updated_at",enterpriseQuery.getStartTime());
                    queryWrapper.le("updated_at",enterpriseQuery.getEndTime());
                }
            }
        }
        return queryWrapper;
    }

    /**
     * 普通帐号的企业查询
     * @param queryWrapper
     * @param account
     * @param enterpriseQuery
     */
    private void commonAccountQuery(QueryWrapper<Enterprise> queryWrapper, Account account, EnterpriseQuery enterpriseQuery){
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", account.getId());
        accountOrganizationQueryWrapper.eq("type", 1);
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        // 兼容旧数据 以前关联企业没有type字段 只要在该表与企业有关系就行
        if(CollectionUtils.isEmpty(accountOrganizations)){
            QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper1 = new QueryWrapper<>();
            accountOrganizationQueryWrapper1.eq("account_id", account.getId());
            accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper1);
        }
        if (CollectionUtils.isEmpty(accountOrganizations)) {
            log.error("该帐号未关联企业信息");
            queryWrapper.eq("id", -1);
        } else {
            List<Integer> collect = accountOrganizations.stream().map(a -> a.getEnterpriseId()).distinct().collect(Collectors.toList());
            if(null != enterpriseQuery && CollectionUtils.isNotEmpty(enterpriseQuery.getIdList())){
                // 普通帐号选择了企业
                if(collect.contains(enterpriseQuery.getIdList().get(0))){
                    queryWrapper.and(wrapper -> wrapper.in("id", enterpriseQuery.getIdList().get(0)).or().in("parent_id", enterpriseQuery.getIdList().get(0)));
                }else{
                    log.warn("当前帐号选择了他并未关联的企业， accountId {}, enterpriseId {}", account.getId(), enterpriseQuery.getIdList().get(0));
                    queryWrapper.eq("id", -1);
                }
            }else{
                if(null != enterpriseQuery && null != enterpriseQuery.getShowChild() && enterpriseQuery.getShowChild()){
                    // 企业管理列表显示运营商+其子企业
                    queryWrapper.and(wrapper -> wrapper.in("id", collect).or().in("parent_id", collect));
                }else{
                    queryWrapper.in("id", collect);
                }
            }
        }
    }

    /**
     * 处理响应参数
     *
     * @param enterpriseList
     */
    private List<EnterpriseDTO> handleResponse(List<Enterprise> enterpriseList) {
        if (CollectionUtils.isEmpty(enterpriseList)) {
            return Collections.emptyList();
        }
        List<EnterpriseDTO> enterpriseDTOList = enterpriseList.stream().map(enterprise -> {
            EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
            BeanUtils.copyProperties(enterprise, enterpriseDTO);
            return enterpriseDTO;
        }).collect(Collectors.toList());
        return enterpriseDTOList;
    }

    /**
     * 删除关联信息
     *
     * @param enterpriseId
     */
    private void deleteRelation(Integer enterpriseId) {
        // 删除企业关联权限
        enterprisePermissionService.deleteEnterprisePermission(Arrays.asList(enterpriseId), null);
        // 删除企业关联app
//        enterpriseAppService.deleteEnterpriseApp(Arrays.asList(enterpriseId), null);

    }

    /**
     * 校验规则：
     * 1、名称全局唯一
     *
     * @param enterprise
     */
    private ResultJson saveCheck(Enterprise enterprise) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Enterprise> codeQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(enterprise.getId())) {
            enterpriseQueryWrapper.ne("id", enterprise.getId());
            codeQueryWrapper.ne("id", enterprise.getId());
        }
        // 名称校验
        enterpriseQueryWrapper.eq("name", enterprise.getName());
//        enterpriseQueryWrapper.eq("industry_id", enterprise.getIndustryId());
        enterpriseQueryWrapper.eq("is_deleted", false);
        if (!enterprise.getType().contains("1")){
            //非运营商在运营商下(包含运营商)验重
            enterpriseQueryWrapper.and(i -> i.eq("parent_id",enterprise.getParentId()).or().eq("id",enterprise.getParentId()));
        }else {
            //运营商在类型下验重
            enterpriseQueryWrapper.like("type",1);
        }
        List<Enterprise> enterprises = enterpriseDao.selectList(enterpriseQueryWrapper);
        if (!CollectionUtils.isEmpty(enterprises)) {
            return ResultJson.fail("企业名称重复");
        }

        // 编码校验
        codeQueryWrapper.eq("code", enterprise.getCode());
        codeQueryWrapper.eq("is_deleted", false);
        List<Enterprise> codeEnterprise = enterpriseDao.selectList(codeQueryWrapper);
        if (!CollectionUtils.isEmpty(codeEnterprise)) {
            return ResultJson.fail("企业编码重复");
        }
        return ResultJson.success();
    }

    public void enterpriseLogRecord(AbstractAccount operateAccount, LogOperationTypeEnum logOperationTypeEnum, String operateContent, Integer entId) {
        OperateLog operateLog = new OperateLog();
        operateLog.setMenu(ModuleTypeEnum.ENTERPRISE_MANAGE.getName());
        operateLog.setOperateType(logOperationTypeEnum.getType());
        operateLog.setOperateContent(operateContent);
        operateLog.setIp(ThreadLocalUtil.getIp());
        operateLog.setIndustryId(ThreadLocalUtil.getIndustryId());
        if (null == operateAccount) {
            operateAccount = ThreadLocalUtil.getAccount();
        }
        if (null != operateAccount) {
            operateLog.setIndustryId(operateAccount.getIndustryId());
            operateLog.setAccountId(operateAccount.getId());
            operateLog.setLoginName(operateAccount.getLoginName());
            operateLog.setName(operateAccount.getName());
            //填充企业ids+项目ids
            Account account = new Account();
            BeanUtils.copyProperties(operateAccount,account);
            List<Enterprise> enterprises = this.list(null,account);
            if (!org.springframework.util.CollectionUtils.isEmpty(enterprises)){
                operateLog.setEnterpriseIds(enterprises.stream().map(Enterprise::getId).collect(Collectors.toList()));
            }
            List<AccountDetailDTO> projectInfoList = accountService.getAccountProjectInfoByIdList(Collections.singletonList(operateAccount.getId()));
            operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            if (!org.springframework.util.CollectionUtils.isEmpty(projectInfoList)){
                operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            }
        }
        logTemplate.addOperateLog(operateLog);
    }

    public void organizationLogRecord(Account operateAccount, LogOperationTypeEnum logOperationTypeEnum, String operateContent, Organization organization) {
        OperateLog operateLog = new OperateLog();
        operateLog.setMenu(ModuleTypeEnum.ORGANIZATION_MANAGE.getName());
        operateLog.setOperateType(logOperationTypeEnum.getType());
        operateLog.setOperateContent(operateContent);
        operateLog.setEnterpriseId(organization.getEnterpriseId());
        operateLog.setIp(ThreadLocalUtil.getIp());
        operateLog.setIndustryId(ThreadLocalUtil.getIndustryId());
        if (null == operateAccount) {
            operateAccount = ThreadLocalUtil.getAccount();
        }
        if (null != operateAccount) {
            operateLog.setIndustryId(operateAccount.getIndustryId());
            operateLog.setAccountId(operateAccount.getId());
            operateLog.setLoginName(operateAccount.getLoginName());
            operateLog.setName(operateAccount.getName());
            //填充企业ids+项目ids
            List<Enterprise> enterprises = this.list(null,operateAccount);
            if (!org.springframework.util.CollectionUtils.isEmpty(enterprises)){
                operateLog.setEnterpriseIds(enterprises.stream().map(Enterprise::getId).collect(Collectors.toList()));
            }
            List<AccountDetailDTO> projectInfoList = accountService.getAccountProjectInfoByIdList(Collections.singletonList(operateAccount.getId()));
            operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            if (!org.springframework.util.CollectionUtils.isEmpty(projectInfoList)){
                operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            }
        }
        logTemplate.addOperateLog(operateLog);

    }

    /**
     * 组装当前创建&修改的企业信息、权限信息发到对应kafka消息队列
     * @param action：create、update
     * @param enterprise
     * @param permissions
     */
    public void sendTenantToMQ(String action, Enterprise enterprise, List<Integer> permissions) {
        if (null != enterprise || CollectionUtils.isNotEmpty(permissions)) {
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "code").in("id", permissions);
            List<Permission> permissionList = permissionDao.selectList(queryWrapper);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("enterprise", enterprise);
            jsonObject.put("permissions", permissionList);
            if (action.equals("create")) {
                entPermissionProducer.createEntPermission(JSONObject.toJSONString(jsonObject));
            } else if (action.equals("update")) {
                entPermissionProducer.updateEntPermission(JSONObject.toJSONString(jsonObject));
            }
        }
    }


    @Override
    public Map<Integer, Account> findEnterpriseAdmin(List<Integer> enterpriseIds) {
        if (enterpriseIds.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        //查询企业的管理员角色
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("enterprise_id", enterpriseIds);
        roleQueryWrapper.eq("type", RoleTypeEnum.MANAGER.code).eq("is_initialized", true).eq("is_deleted", false);
        List<Role> roleEnterpriseList = roleService.list(roleQueryWrapper);
        List<Integer> roleIds = roleEnterpriseList.stream().distinct().map(Role::getId).collect(Collectors.toList());
        //查询角色对应的账号
        QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<AccountRole>().in("role_id", roleIds);
        List<AccountRole> accountRoleList = accountRoleService.list(accountRoleQueryWrapper);
        if (accountRoleList.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        List<Integer> accountIds = accountRoleList.stream().distinct().map(AccountRole::getAccountId).collect(Collectors.toList());
        //查询账号对应的电话
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<Account>().in("id", accountIds);
        List<Account> accountList = accountService.list(accountQueryWrapper);
        if (accountList.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        Map<Integer, Account> enterpriseAdmin = new HashMap<>();
        for (Integer enterpriseId : enterpriseIds) {
            Integer roleId = roleEnterpriseList.stream().filter(p -> p.getEnterpriseId().equals(enterpriseId)).collect(Collectors.toList()).get(0).getId();
            Integer accountId = accountRoleList.stream().filter(p -> p.getRoleId().equals(roleId)).collect(Collectors.toList()).get(0).getAccountId();
            //找到企业的角色-->找到角色的账号
            enterpriseAdmin.put(enterpriseId, accountList.stream().filter(l -> l.getId().equals(accountId)).collect(Collectors.toList()).get(0));
        }
        return enterpriseAdmin;
    }

    @Override
    public List countCatrgoryByFloorOrg(Integer floorOrgId) {
        if (null == floorOrgId) {
            return Collections.EMPTY_LIST;
        }
        List<Integer> floorOrgIdList = new ArrayList<>();
        floorOrgIdList.add(floorOrgId);
        Map<Integer, List<Integer>> floorOrgEnterprises = findAllEnterpriseByFloorOrg(floorOrgIdList);
        if (floorOrgEnterprises.get(floorOrgId).isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<Map<String, String>> catgoryEnterprises = findCatgoryByEnterpriseIds(floorOrgEnterprises.get(floorOrgId));
        Map<String, List<Map<String, String>>> catrgoryEntpriseMap = catgoryEnterprises.stream().collect(Collectors.groupingBy(map -> map.get("cusBuzCatrgoryId")));
        List<Map> returnList = new ArrayList<>();
        for (String cusBuzCatrgoryId : catrgoryEntpriseMap.keySet()) {
            Map<String, Object> catgoryMessageMap = new HashMap<>();
            catgoryMessageMap.put("cusBuzCatrgoryId", cusBuzCatrgoryId);
            catgoryMessageMap.put("cusBuzCatrgoryName", catrgoryEntpriseMap.get(cusBuzCatrgoryId).get(0).get("cusBuzCatrgoryName"));
            List<Map<String, Object>> listMap = new ArrayList<>();
            catrgoryEntpriseMap.get(cusBuzCatrgoryId).forEach(p -> {
                Map<String, Object> entMap = new HashMap<>();
                entMap.put("enterpriseId", p.get("enterpriseId"));
                entMap.put("enterpriseName", p.get("enterpriseName"));
                listMap.add(entMap);
            });
            catgoryMessageMap.put("enterpriseList", listMap);
            returnList.add(catgoryMessageMap);
        }
        return returnList;
    }


    /**
     * 企业管理--查询楼层下所有企业
     *
     * @param floorOrganizationIdList
     * @return
     */
    public Map findAllEnterpriseByFloorOrg(List<Integer> floorOrganizationIdList) {
        //查询楼层及其下所有路址  floor--org map
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<Organization>().in("id", floorOrganizationIdList);
        List<Organization> floorList = organizationService.list(organizationQueryWrapper);
        Map<Integer, List<Organization>> floorOrgMap = new HashMap<>();
        for (Integer floorOrganizationId : floorOrganizationIdList) {
            List<Organization> childrenList = floorList.stream().filter(l -> l.getId().equals(floorOrganizationId)).collect(Collectors.toList());
            if (!childrenList.isEmpty()){
                fingAllChildren(childrenList);
            }
            floorOrgMap.put(floorOrganizationId, childrenList);
        }
        //查询所有符合条件的企业
        List<Organization> organizationList = new ArrayList<>();
        for (Integer floorOrganizationId : floorOrgMap.keySet()) {
            organizationList.addAll(floorOrgMap.get(floorOrganizationId));
        }
        if (organizationList.isEmpty()){
            return floorOrgMap;
        }
        //org--entprise map
        List<Integer> orgIdList = organizationList.stream().map(Organization::getId).distinct().collect(Collectors.toList());
        QueryWrapper<EnterpriseSpace> enterpriseSpaceQueryWrapper = new QueryWrapper<EnterpriseSpace>().in("organization_id", orgIdList);
        List<EnterpriseSpace> enterpriseSpaceList = enterpriseSpaceService.list(enterpriseSpaceQueryWrapper);
        Map<Integer, List<EnterpriseSpace>> organizationSpaseMap = enterpriseSpaceList.stream().collect(Collectors.groupingBy(EnterpriseSpace::getOrganizationId));
        //获取floorid--entid map
        Map<Integer, List<Integer>> floorEnterpriseMap = new HashMap<>();
        for (Integer floorOrganizationId : floorOrganizationIdList) {
            List<Integer> enterpriseList = new ArrayList<>();
            List<Organization> organizations = floorOrgMap.get(floorOrganizationId);
            for (Integer organization : organizationSpaseMap.keySet()) {
                List<Integer> orgIds = organizations.stream().map(Organization::getId).collect(Collectors.toList());
                if (orgIds.contains(organization)) {
                    List<Integer> enterpriseIds = organizationSpaseMap.get(organization).stream().map(EnterpriseSpace::getEnterpriseId).distinct().collect(Collectors.toList());
                    enterpriseList.addAll(enterpriseIds);
                }
            }
            List<Integer> filterList = enterpriseList.stream().distinct().collect(Collectors.toList());
            floorEnterpriseMap.put(floorOrganizationId, filterList);
        }
        return floorEnterpriseMap;
    }

    /**
     * 查找 organization 下的所有子路址节点
     *
     * @param list
     */
    private void fingAllChildren(List<Organization> list) {
        //过滤最高等级路址
        List<Organization> levelSortedList = list.stream().sorted(Comparator.comparing(l -> l.getLevel())).collect(Collectors.toList());
        Collections.reverse(levelSortedList);
        Integer maxlevel = levelSortedList.get(0).getLevel();
        List<Integer> orgIds = list.stream().filter(q -> q.getLevel().equals(maxlevel)).map(Organization::getId).distinct().collect(Collectors.toList());
        //查询子节点
        List<Organization> organizations = organizationService.list(new QueryWrapper<Organization>().in("parent_id", orgIds));
        List<Organization> filterOrgs = organizations.stream().filter(p -> !list.contains(p)).collect(Collectors.toList());
        //子节点不为空继续
        if (!filterOrgs.isEmpty()) {
            list.addAll(organizations);
            list.stream().distinct().collect(Collectors.toList());
            fingAllChildren(list);
        }
    }

    /**
     * 企业管理--查询企业的经营品类
     *
     * @param enterpriseList
     * @return
     */
    public List findCatgoryByEnterpriseIds(List<Integer> enterpriseList) {
        List<Enterprise> EnterpriseList = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseList).eq("status", 1).eq("is_deleted", 0));
        List<EnterpriseExtra> EnterpriseExtraList = enterpriseExtraService.list(new QueryWrapper<EnterpriseExtra>().in("enterprise_id", enterpriseList));
        List<Map<String, String>> catgoryEnterpriseList = new ArrayList<>();
        for (Integer enterpriseId : enterpriseList) {
            List<Enterprise> enterprise = EnterpriseList.stream().filter(p -> p.getId().equals(enterpriseId)).collect(Collectors.toList());
            List<EnterpriseExtra> extra = EnterpriseExtraList.stream().filter(p -> p.getEnterpriseId().equals(enterpriseId)).collect(Collectors.toList());
            EnterpriseExtra enterpriseExtra = extra.get(0);
            JSONObject jsonObject = JSONObject.parseObject(enterpriseExtra.getJson());
            if (null != jsonObject.get("customerInformation")) {
                CustomerInformationVO customerInformationVO = JSONObject.parseObject(String.valueOf(jsonObject.get("customerInformation")), CustomerInformationVO.class);
                //获取经营品类
                List<JSONObject> cusBuzCatrgoryList = customerInformationVO.getCusBuzCatrgory();
                for (JSONObject object : cusBuzCatrgoryList) {
                    Map<String, String> messageMap = new HashMap<>();
                    JSONObject catgoryJson = JSONObject.parseObject(String.valueOf(object));
                    messageMap.put("cusBuzCatrgoryId", String.valueOf(catgoryJson.get("id")));
                    messageMap.put("cusBuzCatrgoryName", String.valueOf(catgoryJson.get("name")));
                    messageMap.put("enterpriseId", String.valueOf(enterprise.get(0).getId()));
                    messageMap.put("enterpriseName", enterprise.get(0).getName());
                    catgoryEnterpriseList.add(messageMap);
                }
            }
        }
        catgoryEnterpriseList.stream().distinct().collect(Collectors.toList());
        return catgoryEnterpriseList;
    }
    @Override
    public List<Enterprise> findEntByOrgids(List<Integer> orgIds) {
        if(CollectionUtils.isEmpty(orgIds)){
            return null;
        }
        QueryWrapper<EnterpriseSpace> enterpriseSpaceQueryWrapper = new QueryWrapper<>();
        enterpriseSpaceQueryWrapper.in("organization_id", orgIds);
        List<EnterpriseSpace> list = enterpriseSpaceService.list(enterpriseSpaceQueryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<Integer> entIds = list.stream().map(i -> i.getEnterpriseId()).collect(Collectors.toList());
        QueryWrapper<Enterprise> entWrapper = new QueryWrapper<>();
        entWrapper.in("id", entIds);
        entWrapper.eq("is_deleted",0);
        //入驻企业
        entWrapper.like("type",2);
        List<Enterprise> ents = enterpriseDao.selectList(entWrapper);
        return ents;
    }

    @Override
    public List<Enterprise> getEntListByAccountId(Integer accountId) {
        if(accountId == null){
            return null;
        }
        //获得账号关联的企业
        QueryWrapper<StaffOrganization> accountOrganizationQueryWrapper1 = new QueryWrapper<>();
        accountOrganizationQueryWrapper1.eq("account_id", accountId);
        List<StaffOrganization> accountOrganizations = staffOrganizationDao.selectList(accountOrganizationQueryWrapper1);
        if(CollectionUtils.isEmpty(accountOrganizations)){
            return null;
        }
        List<Integer> enterpriseIds = accountOrganizations.stream().map(StaffOrganization::getEnterpriseId).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(enterpriseIds)){
            return null;
        }
        //获取入驻企业
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper();
        queryWrapper.in("id",enterpriseIds);
        queryWrapper.eq("is_deleted", false);
        return enterpriseDao.selectList(queryWrapper);
    }
}


